from django.shortcuts import render
from .models import WeatherData
from pyecharts.charts import Line
from pyecharts import options as opts
from django.http import JsonResponse
from django.db.models import Max, Min

def index(request):
    # 获取最近30天的数据
    weather_data = WeatherData.objects.order_by('-date')[:30]
    
    return render(request, 'weather_app/index.html', {
        'weather_data': weather_data,
    })

def get_temperature_chart(request):
    # 获取最近30天的数据
    weather_data = WeatherData.objects.order_by('date')[:30]
    
    dates = [str(data.date) for data in weather_data]
    max_temps = [data.max_temperature for data in weather_data]
    min_temps = [data.min_temperature for data in weather_data]
    
    # 创建图表
    line = Line()
    line.add_xaxis(dates)
    line.add_yaxis("最高气温", max_temps, is_symbol_show=True)
    line.add_yaxis("最低气温", min_temps, is_symbol_show=True)
    
    line.set_global_opts(
        title_opts=opts.TitleOpts(title="近30天气温变化"),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
    )
    
    return JsonResponse({"chart_data": line.dump_options()})
